package com.iap.admin.mediator
{
	import com.iap.admin.view.AdminMenuView;
	import com.iap.admin.view.FillerView;
	import com.iap.admin.view.filler.FillerEditView;
	import com.iap.app.AppGlobal;
	import com.iap.client.event.FillerEvent;
	import com.iap.common.mediator.BaseMediator;
	import com.iap.common.model.Filler;
	import com.iap.common.signal.FillerRequestSignal;
	
	import mx.collections.ArrayCollection;
	import mx.collections.ArrayList;
	
	import spark.components.Group;
	import spark.events.GridEvent;

	public class FillerMediator extends BaseMediator
	{
		[Inject]
		public var view:FillerView;
		[Inject]
		public var request:FillerRequestSignal;
		
		private var createMode:Boolean = false;

		override public function onRegister():void
		{
			view.onOptionClick.add(onClick);
			addContextListener(FillerEvent.RESPONSE, responseHandler);
			addViewListener(GridEvent.GRID_CLICK, gridClickEvent);
			dispatchRequest();
		}
		
		private function gridClickEvent(evt:GridEvent):void
		{ 
			var item:Filler = evt.item as Filler;
			if(item==null) return;
			edit(item);
		}
		
		private function dispatchRequest():void
		{
			AppGlobal.startWait();
			request.dispatch(new Filler(), FillerRequestSignal.GET);
		}
		
		private function responseHandler(evt:FillerEvent):void
		{
			AppGlobal.endWait();
			if(evt.response.task == FillerRequestSignal.SAVE && createMode)
			{
				edit(evt.response.result as Filler);
				createMode = false;
			} else {
				var fillers:Array = evt.response.result as Array;
				view.fillerSolidGrid.dataProvider = new ArrayCollection(fillers.filter(fillerBySolidFilter));
				view.fillerTextureGrid.dataProvider = new ArrayCollection(fillers.filter(fillerByTextureFilter));
			}
		}

		private function fillerBySolidFilter(element:*, index:int, arr:Array):Boolean
		{
			return element.type == 0;
		}
		
		private function fillerByTextureFilter(element:*, index:int, arr:Array):Boolean
		{
			return element.type == 1;
		}
		
		private function onClick(itemName:String):void
		{
			switch(itemName)
			{
				case FillerView.HOME_NAME:
				{
					home();
					break;
				}
				case FillerView.CREATE_NAME:
				{
					create();
					break;
				}
			}
		}
		
		private function home():void
		{
			setView(view.parent as Group, new AdminMenuView(), FX_GLIDE_OUT);
		}
		
		private function create():void
		{
			AppGlobal.startWait();
			createMode = true;
			var empty:Filler = new Filler();
			empty.name = "";
			empty.type = Filler.TYPE_SOLID;
			request.dispatch(empty, FillerRequestSignal.SAVE);
		}
		
		private function edit(item:Filler):void
		{
			var newView:FillerEditView = new FillerEditView();
			newView.onReady.addOnce(function(str:String):void{
				newView.fill(item);
			});
			setView(view.parent as Group, newView);
		}
	}
}